package com.yc.backstage.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.backstage.common.annotation.DataScope;
import com.yc.backstage.common.constant.UserConstants;
import com.yc.backstage.entity.*;
import com.yc.backstage.entity.ao.UserAo;
import com.yc.backstage.entity.dto.UserImExDto;
import com.yc.backstage.entity.vo.QueryUserVo;
import com.yc.backstage.entity.vo.UpdateUserVo;
import com.yc.backstage.mapper.*;
import com.yc.backstage.service.SysUserPostService;
import com.yc.backstage.service.SysUserRoleService;
import com.yc.backstage.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.backstage.utils.SecurityUtils;
import com.yc.common.expection.ServiceException;
import com.yc.common.utils.SpringUtils;
import com.yc.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname SysUserController
 * @Description
 * @Version 1.0.0
 * @Date 2022-08-23 11:49:19
 * @Created by Mikechen
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysPostMapper sysPostMapper;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserPostService sysUserPostService;

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return sysUserMapper.resetUserPwd(userName, password);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return sysUserMapper.updateUser(user);
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = sysPostMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = sysRoleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }


    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return sysUserMapper.selectUserByUserName(userName);
    }

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return sysUserMapper.selectUserList(user);
    }


    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName) {
        int count = sysUserMapper.checkUserNameUnique(userName);
        if (count > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 注册用户
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return sysUserMapper.insert(user) > 0;
    }

    @Override
    public List<SysUser> selectList() {
        return sysUserMapper.selectList(null);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public Page<SysUser> selectPage(QueryUserVo queryUserVo) {
        Page<SysUser> page = new Page<>(queryUserVo.getPageNum(), queryUserVo.getPageSize());
        return sysUserMapper.selectByPage(page, queryUserVo);
    }

    /**
     * 功能描述：根据用户id查询用户信息
     *
     * @author: mikechen
     * @date: 2022/8/23 21:26
     */
    @Override
    public SysUser getUserInfoById(Long userId) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return sysUserMapper.selectOne(wrapper);
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = sysUserMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 添加用户
     *
     * @param user
     */
    @Override
    public int insertUser(SysUser user) {
        //用户密码加密
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        //创建人
        user.setCreateBy(SecurityUtils.getUsername());
        //创建时间
        user.setCreateTime(LocalDateTime.now());
        //插入用户记录
        int rows = sysUserMapper.insert(user);
        // 新增用户岗位关联
        sysUserPostService.insertUserPost(user);
        // 新增用户与角色管理
        sysUserRoleService.insertUserRole(user);
        return rows;

    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 根据用户id查询用户
     *
     * @param userId
     * @return
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return sysUserMapper.selectUserById(userId);
    }

    /**
     * 根据用户id删除用户
     *
     * @param ids
     */
    @Override
    public int removeUserById(List<Long> ids) {
        sysUserMapper.deleteUserById(ids);
        for (Long userId : ids) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            checkUserAllowed(user);
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        sysUserRoleService.deleteUserRole(ids);
        // 删除用户与岗位关联
        sysUserPostService.deleteUserPost(ids);
        return sysUserMapper.deleteUserByIds(ids);
    }

    /**
     * 修改用户信息
     *
     * @param user
     */
    @Override
    public void updateUserInfo(SysUser user) {
        //用户密码加密
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        sysUserMapper.updateById(user);
    }

    @Override
    public void changeUserStatus(Long userId, String status) {
        SysUser user = sysUserMapper.selectById(userId);
        sysUserMapper.updateUser(user);
    }

    /**
     * 修改密码
     *
     * @return
     */
    @Override
    public void updatePassword(UpdateUserVo user) {
        UpdateWrapper<SysUser> wrappr = new UpdateWrapper<>();
        wrappr.eq("user_id", user.getUserId());
        SysUser sysUser = new SysUser();
        user.setUserId(user.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(user.getNewPassword()));
        sysUser.setUserId(user.getUserId());
        sysUserMapper.update(sysUser, wrappr);
    }

    /**
     * 根据用户id组装导出数据信息
     *
     * @param ids
     * @return
     */
    @Override
    public List<UserImExDto> getListUserByIds(List<Long> ids) {
        List<SysUser> listUser = sysUserMapper.selectUserByIds(ids);
        return null;
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public List<UserImExDto> getUserAll() {
        return sysUserMapper.selectUserAll();
    }

    /**
     * 查询当前用户个人信息
     *
     * @return
     */
    @Override
    public UserAo getUserProfile() {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        return sysUserMapper.getUserInfo(userId);
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        sysUserRoleService.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        sysUserRoleService.insertUserRole(user);
        // 删除用户与岗位关联
        sysUserPostService.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        sysUserPostService.insertUserPost(user);
        return sysUserMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return sysUserMapper.updateUser(user);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return sysUserMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        sysUserRoleService.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }


    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            sysRoleMapper.batchUserRole(list);
        }
    }
}
